<template>
  <div class="login-container">
    <div class="login-form">
      <h2>用户登录</h2>
      <form @submit.prevent="handleSubmit">
        <div class="form-group">
          <label for="username">用户名：</label>
          <input
            type="text"
            id="username"
            v-model="form.username"
            placeholder="请输入用户名"
            required
          />
        </div>
        <div class="form-group">
          <label for="password">密码：</label>
          <input
            type="password"
            id="password"
            v-model="form.password"
            placeholder="请输入密码"
            required
          />
        </div>
        <div class="button-group">
          <button type="button" class="btn-clear" @click="handleClear">
            清空
          </button>
          <button type="submit" class="btn-submit" :disabled="loading">
            {{ loading ? '登录中...' : '提交' }}
          </button>
        </div>
      </form>
      <div v-if="errorMessage" class="error-message">
        {{ errorMessage }}
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { apiService } from '../utils/http'
import { tools } from '../utils/tools'

export default {
  name: 'LoginPage',
  setup() {
    const router = useRouter()
    const route = useRoute()
    const form = ref({
      username: 'sivan',
      password: ''
    })
    const publicKey = ref('')
    const loading = ref(false)
    const errorMessage = ref('')

    // 获取公钥
    const fetchPublicKey = async () => {
      try {
        const response = await apiService.getFresh('/PublicKeyQuery')
        if (response.data.key == "") {
          throw new Error('获取公钥失败')
        }
        publicKey.value = response.data.key
      } catch (error) {
        console.error('获取公钥失败:', error)
        errorMessage.value = '获取公钥失败，请刷新页面重试'
      }
    }

    // 设置cookie
    const setCookie = (name, value, hours) => {
      const date = new Date()
      date.setTime(date.getTime() + hours * 60 * 60 * 1000)
      const expires = `expires=${date.toUTCString()}`
      document.cookie = `${name}=${value}; ${expires}; path=/`
    }

    // 处理提交
    const handleSubmit = async () => {
      if (!form.value.username || !form.value.password) {
        errorMessage.value = '请输入用户名和密码'
        return
      }

      loading.value = true
      errorMessage.value = ''

      try {
        // 加密密码
        const encryptedPassword = await tools.encryptPassword(publicKey.value, form.value.password)
        // 调用登录接口
        const response = await apiService.post('/Login', {
          username: form.value.username,
          password: encryptedPassword
        })

        if (response.data.status) {
          setCookie('token', response.data.token, 1)
          const returnUrl = route.query.returnUrl
          if (returnUrl) {
            router.push(returnUrl)
          }
          // router.push('/personal')
        } else {
          errorMessage.value = '用户名或密码错误'
        }
      } catch (error) {
        console.error('登录失败:', error)
        errorMessage.value = '登录失败，请重试'
      } finally {
        loading.value = false
      }
    }

    // 处理清空
    const handleClear = () => {
      form.value.username = 'sivan'
      form.value.password = ''
      errorMessage.value = ''
    }

    // 页面加载时获取公钥
    onMounted(() => {
      fetchPublicKey()
    })

    return {
      form,
      loading,
      errorMessage,
      handleSubmit,
      handleClear
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.login-form {
  background: white;
  padding: 2rem;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 400px;
}

.login-form h2 {
  text-align: center;
  margin-bottom: 1.5rem;
  color: #333;
}

.form-group {
  margin-bottom: 1rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  color: #555;
  font-weight: 500;
}

.form-group input {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
  box-sizing: border-box;
}

.form-group input:focus {
  outline: none;
  border-color: #007bff;
}

.button-group {
  display: flex;
  gap: 1rem;
  margin-top: 1.5rem;
}

.button-group button {
  flex: 1;
  padding: 0.75rem;
  border: none;
  border-radius: 4px;
  font-size: 1rem;
  cursor: pointer;
  transition: background-color 0.3s;
}

.btn-clear {
  background-color: #6c757d;
  color: white;
}

.btn-clear:hover {
  background-color: #5a6268;
}

.btn-submit {
  background-color: #007bff;
  color: white;
}

.btn-submit:hover:not(:disabled) {
  background-color: #0056b3;
}

.btn-submit:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.error-message {
  margin-top: 1rem;
  padding: 0.75rem;
  background-color: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
  border-radius: 4px;
  text-align: center;
}
</style>